package com.exp.bookhouse.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exp.bookhouse.pojo.Book;
import com.exp.bookhouse.pojo.Category;
import com.exp.bookhouse.service.BookService;
import com.exp.bookhouse.service.CategoryService;
import com.exp.bookhouse.util.AmountUtil;
import com.exp.bookhouse.util.ApiJSONResult;
import com.exp.bookhouse.util.DateUtil;
import io.swagger.annotations.*;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(value = "书籍管理接口",tags = "管理员管理书籍操作")
@Controller
@RequestMapping("/admin")
public class BookControllerAdmin {

    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    private String name;


    @ApiOperation(value = "查询书籍列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "p", value = "页数", required = false, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "s", value = "显示记录数", required = false, dataType = "Int")
    })
    @GetMapping("/toBook")
    public String toBook(@RequestParam(value = "p", required = false, defaultValue = "1")Integer page,
                         @RequestParam(value = "s", required = false, defaultValue = "5")Integer size,
                         Model model){
        IPage<Book> iPage = bookService.queryBookByPage(page,size);//分页查询书籍列表
        model.addAttribute("iPage",iPage);
        return "book";
    }


    @ApiOperation(value = "查询书籍细节")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "书籍id", required = true, dataType = "Long")
    })
    @GetMapping("/queryBookDetail/{id}")
    public String queryBookDetail(@PathVariable("id")Long id, Model model){
        Book book = bookService.queryBookById(id);//根据书籍id查询书本信息
        model.addAttribute("book",book);
        return "bookDetail";
    }


    @ApiOperation(value = "查找书籍")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "name", value = "书籍名称", required = true, dataType = "String"),
    })
    @PostMapping("/searchBook")
    public String searchBook(@RequestParam("name")String name, Model model){
        List<Book> iPage = bookService.getBookByName(name);
        model.addAttribute("iPage",iPage);
        return "bookSearchResult";
    }


    @GetMapping("/toSaveBook")
    public String toSaveBook(Model model){
        List<Category> categories = categoryService.queryAllCategory();
        model.addAttribute("categories",categories);
        return "bookAdd";
    }


    @ApiOperation(value = "保存书籍信息")
    @PostMapping("/saveBook")
    public @ResponseBody
    ApiJSONResult saveBook(@ApiParam(value = "书籍信息",required = true) @RequestBody Book book) throws Exception {
        bookService.saveBook(book);
        return ApiJSONResult.ok(book);
    }


    @ApiOperation(value = "跳转书籍更新")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "书籍id", required = true, dataType = "Long")
    })
    @GetMapping("/toUpdateBook/{id}")
    public String toUpload(@PathVariable("id")Long id, Model model){
        List<Category> categories = categoryService.queryAllCategory();
        Book book = bookService.queryBookById(id);
        model.addAttribute("categories",categories);
        model.addAttribute("book",book);
        return "bookUpdate";
    }


    @ApiOperation(value = "保存书籍轮播图")
    @PostMapping("/uploadImage")
    public @ResponseBody ApiJSONResult uploadImage(@ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws IOException {
        if(file == null || file.length <= 0){
            return ApiJSONResult.ok();
        }
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        Map<String, String[]> parameterMap = multipartRequest.getParameterMap();
        String id = parameterMap.get("id")[0];  //书籍id

        bookService.updateBookById(id,file);
        return ApiJSONResult.ok();
    }



    @ApiOperation(value = "删除书籍轮播图")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "书籍id", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "key", value = "轮播图路径", required = true, dataType = "String")
    })
    @PostMapping("/deleteImage")
    public @ResponseBody ApiJSONResult deleteImage(@RequestParam("key")String url, @RequestParam("id")Long id,Model model) throws Exception {
        Book book = bookService.deleteImage(id,url);
        model.addAttribute("book",book);
        return ApiJSONResult.ok();
    }



    @ApiOperation(value = "更新书籍")
    @PostMapping("/updateBook")
    public @ResponseBody ApiJSONResult updateBook(@ApiParam(value = "书籍信息",required = true)@RequestBody Book book){
        System.out.println(book);
        bookService.updateBookById(book);
        return ApiJSONResult.ok(book);
    }


    @ApiOperation(value = "删除书籍")
    @GetMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable("id")Long id){
        bookService.deleteBook(id);
        return "redirect:/admin/toBook";
    }


    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }


    @ApiOperation(value = "导出书籍列表")
    @RequestMapping("/exportBook")
    @ResponseBody
    public int exportBook() {
        List<Book> books = new ArrayList<>();
        books = bookService.queryAllBook();
        return exportExcelPaper(books);
    }
    public int exportExcelPaper(List<Book> lists) {
        // 标题
        String[] title = { "书名", "作者", "单价", "书本描述", "出版社", "轮播图片", "库存","更新时间"};
        // 创建一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表sheet
        HSSFSheet sheet = workbook.createSheet();
        // 设置列宽
        setColumnWidth(sheet, 8);
        // 创建第一行
        HSSFRow row = sheet.createRow(0);
        // 创建一个单元格
        HSSFCell cell = null;
        // 创建表头
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            // 设置样式
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            // 设置字体
            HSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            // font.setFontHeight((short)12);
            font.setFontHeightInPoints((short) 13);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);

            cell.setCellValue(title[i]);
        }
        // 从第二行开始追加数据
        for (int i = 1; i < (lists.size() + 1); i++) {
            // 创建第i行
            HSSFRow nextRow = sheet.createRow(i);
            for (int j = 0; j < 8; j++) {
                Book book = lists.get(i-1);
                HSSFCell cell2 = nextRow.createCell(j);
                if (j == 0) {
                    cell2.setCellValue(book.getName());
                }
                if (j == 1) {
                    cell2.setCellValue(book.getAuthor());
                }
                if (j == 2) {
                    String str = AmountUtil.changeF2Y(book.getPrice());
                    cell2.setCellValue(str);
                }
                if (j == 3) {
                    cell2.setCellValue(book.getDescription());
                }
                if (j == 4) {
                    cell2.setCellValue(book.getPublishHouse());
                }
                if (j == 5) {
                    cell2.setCellValue(book.getPic());
                }
                if (j == 6) {
                    cell2.setCellValue(book.getStock());
                }
                if (j == 7) {
                    String date = DateUtil.formatTimesTampDate(book.getUpdateTime());
                    cell2.setCellValue(date);
                }
            }
        }

        // 临时创建一个文件
        File file = new File("E:/book.xls");
        try {
            file.createNewFile();
            // 打开文件流
            FileOutputStream outputStream = FileUtils.openOutputStream(file);
            workbook.write(outputStream);
            outputStream.close();
            return 1;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return -1;
    }
    // 设置列宽()
    private static void setColumnWidth(HSSFSheet sheet, int colNum) {
        for (int i = 0; i < colNum; i++) {
            int v = 0;
            v = Math.round(Float.parseFloat("15.0") * 37F);
            v = Math.round(Float.parseFloat("20.0") * 267.5F);
            sheet.setColumnWidth(i, v);
        }
    }


    @ApiOperation(value = "下载书籍列表")
    @PostMapping("/downloadBook")
    public void downloadBook(HttpServletResponse response, Model model) {
        //待下载文件名
        String fileName = "book.xls";
        //设置为png格式的文件
        response.setHeader("content-type", "application/x-xls");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File("E:/" + fileName )));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path = "E:/" + fileName;//临时创建的表格路径
        File file = new File(path);
        if(file.exists()){//文件存在删除文件
            file.delete();
        }
    }

}
